/**
go run fetchall.go  http://www.open-open.com/lib/view/open1396578860887.html https://www.baidu.com/index.php?tn=request_18_pg
2018/7/28
wgg
*/
package main

import (
	"time"
	"os"
	"net/http"
	"fmt"
	"io"
	"io/ioutil"
)

func main() {
	start := time.Now()
	ch := make(chan string)
	for _,url := range os.Args[1:]{
		go fetch(url,ch) //使用go关键字启动一个goroutine
	}
	//根据前端传入的次数获取相应多次的返回数据
	for range os.Args[1:]{
		fmt.Println(<-ch)//从通道ch接收
	}
	fmt.Printf("%.2fs elapsed\n",time.Since(start).Seconds())
}


func fetch(url string,ch chan <- string){
	start := time.Now()
	resp,err := http.Get(url)
	if err != nil {
		ch <- fmt.Sprint(err)//发送到通道ch
		return
	}

	nbytes,err := io.Copy(ioutil.Discard,resp.Body)//将resp.Body的数据拷贝到ioutil.Discard
	resp.Body.Close()
	if err != nil {
		ch <- fmt.Sprintf("while reading %s : %v ",url,err)
		return
	}

	secs := time.Since(start).Seconds()
	ch <- fmt.Sprintf("%.2fs %7d %s",secs,nbytes,url)
}
